<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="报工产线" prop="lineId">
        <el-select v-model="queryParams.lineId" class="!w-160px" clearable disabled placeholder="">
          <el-option
            v-for="item in getIntDictOptions(DICT_TYPE.OPTICORE_LINE)"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="工序" prop="process">
        <el-select
          v-model="queryParams.processCode"
          class="!w-160px"
          clearable
          disabled
          placeholder=""
        >
          <el-option
            v-for="item in processList"
            :key="item.processCode"
            :label="item.processName"
            :value="item.processCode"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div class="serial-number">
      <el-input
        v-model="serial"
        style="max-width: 600px"
        placeholder="请扫描物料序列号"
        clearable
        class="input-with-select"
        @clear="handleSerialClear"
        @keyup.enter="handleSerialSearch"
      >
        <template #prepend>
          <el-select v-model="queryParams.typeId" style="width: 115px" placeholder="请选择类型">
            <el-option
              v-for="dict in getIntDictOptions('detection_type')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" @click="handleSerialSearch" />
        </template>
      </el-input>
    </div>

    <!-- 工单信息展示区域 -->
    <div v-if="inspectionData" class="inspection-info">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">工单号：</span>
            <span class="info-value">{{ inspectionData.docNo }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">工单数量：</span>
            <span class="info-value">{{ inspectionData.qty || '--' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">物料品号：</span>
            <span class="info-value">{{ inspectionData.itemCode }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <span class="info-label">规格：</span>
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="inspectionData.itemSpecification"
              placement="top-start"
            >
              <span class="info-value ellipsis">{{ inspectionData.itemSpecification }}</span>
            </el-tooltip>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 检验项目列表 -->
    <div style="margin-top: 10px">
      <h3>检验项目列表</h3>
      <div style="display: flex; margin-top: 20px; justify-content: space-between">
        <el-form-item label="检验类别:" prop="typeId">
          <el-select v-model="detectionType" placeholder="请选择检测类型" class="!w-100px">
            <el-option
              v-for="dict in paramsTypes"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <div class="action-buttons">
          <el-button type="success" @click="handleSubmit('pass')">合格</el-button>
          <el-button v-if="queryParams.typeId == 1" type="danger" @click="handleSubmit('no-pass')"
            >不合格
          </el-button>
          <el-button v-if="queryParams.typeId == 2" type="warning" @click="handleSubmit('rework')"
            >返工
          </el-button>
          <el-button v-if="queryParams.typeId == 2" type="danger" @click="handleSubmit('scrap')"
            >报废
          </el-button>
        </div>
      </div>
    </div>

    <!--    <div
          v-if="inspectionData && inspectionData.recordItemList && inspectionData.recordItemList.length > 0"
          class="inspection-items">
          <el-table :data="inspectionData.recordItemList" border style="width: 100%">
            <el-table-column prop="itemCode" label="检验项目编码" width="180" />
            <el-table-column prop="itemName" label="检验项目名称" width="180" />
            <el-table-column prop="paramMin" label="最小值" />
            <el-table-column prop="paramMax" label="最大值" />
            <el-table-column label="检验值">
              <template #default="scope">
                <el-input
                  v-model="scope.row.detectionValue"
                  placeholder="请输入检验值"
                  @blur="handeValueBlur(scope.row)"
                  @keyup.enter="handeValueBlur(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="检验结果">
              <template #default="scope">
                <el-select v-model="scope.row.status" clearable placeholder="请选择结果">
                  <el-option label="pass" value="OK" />
                  <el-option label="fail" value="NG" />
                </el-select>
              </template>
            </el-table-column>
          </el-table>

          <div class="action-buttons">
            <el-button type="success" @click="handleSubmit('pass')">合格</el-button>
            <el-button v-if="queryParams.typeId == 1" type="danger" @click="handleSubmit('no-pass')">不合格
            </el-button>
            <el-button v-if="queryParams.typeId == 2" type="warning" @click="handleSubmit('rework')">返工
            </el-button>
            <el-button v-if="queryParams.typeId == 2" type="danger" @click="handleSubmit('scrap')">报废
            </el-button>
          </div>
        </div>-->

    <div
      v-if="metricsTitles.length > 0 && metricsItemTableData.length > 0"
      class="inspection-table"
    >
      <div class="table-scroll-wrapper">
        <table class="custom-table">
          <thead>
            <tr>
              <!-- 左上角斜线单元格 -->
              <th class="sticky-header sticky-column diagonal-header" style="z-index: 99">
                <!-- <div class="top-text">检测项目名称</div>
                <div class="bottom-text">检测值录入</div> -->
                <img src="/src/assets/imgs/tab.png" alt="" style="width: 100%; height: 100%" />
              </th>
              <!-- 动态列头 -->
              <th v-for="(col, colIndex) in metricsTitles" :key="colIndex" class="sticky-header">
                {{ col }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, rowIndex) in metricsItemTableData" :key="rowIndex">
              <td class="label-cell sticky-column">
                <span style="color: #606266; font-size: 14px" v-if="row.isEdit">{{
                  row.label
                }}</span>
                <el-input v-else v-model="row.label" />
                <el-icon class="edit-icon" @click="editRow(row)">
                  <Edit />
                </el-icon>
              </td>

              <td v-for="(value, colIndex) in row.values" :key="colIndex">
                <el-input
                  v-if="checkShowInput(rowIndex, colIndex)"
                  v-model="row.values[colIndex]"
                  @blur="handleValueCheck(row, colIndex)"
                  :class="getCellClass(row.statuses[colIndex])"
                  placeholder="请输入检测值"
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑检测值名称"
      width="300px"
      :close-on-click-modal="false"
    >
      <el-input v-model="editingLabel" placeholder="请输入新的名称" @keyup.enter="saveEdit" />
    </el-dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue' // 导入图标，这里用Search代替二维码图标
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { InspectionRecordApi } from '@/api/opticore/inspection/record'
import { ProcessInfoApi } from '@/api/opticore/processinfo'

import { ref, onMounted } from 'vue'
import { Edit } from '@element-plus/icons-vue'

// 计算对角线角度
const calculateDiagonalAngle = () => {
  const header = document.querySelector('.diagonal-header')
  if (header) {
    const width = header.offsetWidth
    const height = header.offsetHeight
    const angle = Math.atan(height / width) * (180 / Math.PI)
    const length = Math.sqrt(width * width + height * height)
    document.documentElement.style.setProperty('--diagonal-angle', `${angle}deg`)
    document.documentElement.style.setProperty('--diagonal-width', `${(length / width) * 100}%`)
  }
}

/** 报工记录 列表 */
defineOptions({ name: 'WorkReport' })

// 假设每行4个值列
const metricsTitles = ref([])

// 每个检测项的检测值个数
const metricsMaxSize = ref([])

//const metricsItemIdRef = ref([])

// 每行数据
const metricsItemTableData = ref([])
const detectionType = ref('')
// 记录每行已输入的检测值数量
const inputCounts = ref({})

const paramsTypes = ref([])

// 编辑对话框相关数据
const editDialogVisible = ref(false)
const editingRow = ref(null)
const editingLabel = ref('')

// 编辑操作
function editRow(row) {
  // editingRow.value = row
  // editingLabel.value = row.label
  // editDialogVisible.value = true

  metricsItemTableData.value = metricsItemTableData.value.map((item) => {
    if (row == item) {
      console.log(1, item)

      return {
        ...item,
        isEdit: !item.isEdit
      }
    } else {
      console.log(2, item)
      return {
        ...item,
        isEdit: true
      }
    }
  })
}

// 保存编辑
function saveEdit() {
  if (editingRow.value) {
    editingRow.value.label = editingLabel.value
  }
  editDialogVisible.value = false
}

// 控制单元格样式
function getCellClass(status) {
  if (status === 'NG') return 'cell-red'
  if (status === 'OK') return 'cell-green'
  return ''
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const serial = ref('') //物料序列号
const productLineList = ref([])
const processList = ref([])
const inspectionData = ref(null) // 存储检验数据
const typeList = ref([
  { label: '首检', value: 1 },
  { label: '工序检', value: 2 }
])
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serialNo: '',
  lineId: '',
  processCode: '',
  typeId: getIntDictOptions('detection_type')[0].value
})
const queryFormRef = ref() // 搜索的表单

/** 初始化 **/
onMounted(() => {
  fetchProcessList()
  paramsTypes.value = getStrDictOptions(DICT_TYPE.ARGS_VALUE_TYPE)
  detectionType.value = paramsTypes.value[0]
})

// 监听物料序列号变化
/*watch(serial, async (newVal, oldVal) => {
  if (newVal != oldVal) {
    console.log(newVal)
  }
})*/

watch(queryParams, (newVal, oldVal) => {
  metricsItemTableData.value = []
  if (newVal.processCode) {
    handleSerialSearch()
  }
})

// 监听检验类别变化
watch(detectionType, (newVal, oldVal) => {
  if (newVal !== oldVal && oldVal !== '') {
    handleSerialSearch()
  }
})

// 获取所有工序
const fetchProcessList = async () => {
  try {
    processList.value = await ProcessInfoApi.fetchProcessDoList()
  } finally {
  }
}
const checkShowInput = (rowIndex: number, colIndex: number) => {
  if (rowIndex + 1 > metricsMaxSize.value[colIndex]) return false
  return true
}

// 检查输入值是否在范围内
const handleValueCheck = (row, colIndex: number) => {
  const value = row.values[colIndex]
  if (!value || !inspectionData.value?.recordItemList) {
    row.statuses[colIndex] = ''
    return
  }

  const item = inspectionData.value.recordItemList[colIndex]
  if (!item) return

  // 如果是非数值类型的检测项，不进行范围校验
  if (item.paramType === '3') {
    row.statuses[colIndex] = ''
    return
  }
  if (isNaN(value)) {
    message.warning('请输入有效的数字')
    row.statuses[colIndex] = 'NG'
    return
  }
  const numValue = parseFloat(value)

  const hasMin = !isNaN(parseFloat(item.paramMin))
  const hasMax = !isNaN(parseFloat(item.paramMax))
  const min = hasMin ? parseFloat(item.paramMin) : null
  const max = hasMax ? parseFloat(item.paramMax) : null

  if (!hasMin && !hasMax) {
    row.statuses[colIndex] = ''
    return
  }

  if ((hasMin && numValue < min) || (hasMax && numValue > max)) {
    const range =
      hasMin && hasMax ? `${min} ~ ${max}` : hasMin ? `>= ${min}` : hasMax ? `<= ${max}` : ''
    message.warning(`输入值不在有效范围内：${range}`)
    row.statuses[colIndex] = 'NG'
  } else {
    row.statuses[colIndex] = 'OK'
  }
}

const startTime = ref('');
const endTime = ref('');

const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const handleSerialSearch = async () => {
  // 2. 记录开始时间（前端执行时）
  startTime.value = getCurrentTime()

  if (!queryParams.typeId) {
    message.warning('请选择检验类型')
    return
  }

  if (queryParams.typeId === 3) {
    message.warning('功能未开发，敬请期待')
    return
  }

  if (!serial.value) {
    message.warning('请扫描物料序列号')
    return
  }

  // 在这里实现你的逻辑
  //console.log('回车键被按下，触发方法，序列号：', serial.value, detectionType.value)
  const params = {
    type: queryParams.typeId,
    serialNo: serial.value,
    paramType: detectionType.value
  }
  try {
    const data = await InspectionRecordApi.getInspectionRecordQuery(params)
    if (!data) return
    // 更新状态
    inspectionData.value = data
    queryParams.lineId = data.lineId
    queryParams.processCode = data.processCode
    // 为每个检验项目添加检验结果和状态字段
    if (inspectionData.value.recordItemList && inspectionData.value.recordItemList.length > 0) {
      inspectionData.value.recordItemList.forEach((item) => {
        item.status = ''
      })
    }
    metricsTitles.value = data.recordItemList.map((row) => row.itemName)
    metricsMaxSize.value = data.recordItemList.map((row) => row.nums)
    //metricsItemIdRef.value = data.recordItemList.map((row) => row.itemId)

    // 生成表格数据
    const maxNums = Math.max(...data.recordItemList.map((item) => item.nums || 0))
    metricsItemTableData.value = Array.from({ length: maxNums }, (_, i) => ({
      label: `检测值${i + 1}`,
      isEdit: true,
      values: Array(metricsTitles.value.length).fill(''),
      statuses: Array(metricsTitles.value.length).fill(''),
      itemIds: data.recordItemList.map((row) => row.itemId)
    }))
  } catch (error) {
    inspectionData.value.recordItemList = []
  }
}

const handleSubmit = async (type) => {
  endTime.value = getCurrentTime()
  if (metricsItemTableData.value.length === 0) {
    console.warn('metricsItemTableData.isEmpty')
    return
  }
  // 根据不同类型处理提交逻辑
  const statusMap = {
    pass: 1, // 合格
    'no-pass': 2, // 不合格
    rework: 3,
    scrap: 4 // 报废
  }
  // 检查是否所有检验项都已填写
  /*
    const allFilled = inspectionData.value.recordItemList.every(item => item.detectionValue)
    if (!allFilled) {
    message.warning('请填写所有检验项的检验结果')
    return
  }*/

  if (serial.value === '') {
    message.warning('请扫描物料序列号')
    return
  }

  // 这里可以调用创建检验记录的API
  const inspectionRecordVO = {
    serialNo: serial.value, // 序列号（物料编号）
    docNo: inspectionData.value.docNo, // 工单号
    materialsNum: inspectionData.value.itemCode, // 物料品号
    typeId: queryParams.typeId, // 检验类型id（字典维护）
    lineId: queryParams.lineId, // 产线id
    processCode: queryParams.processCode, // 工序id
    status: statusMap[type],
    remark: '', // 备注
    creatorName: JSON.parse(localStorage.getItem('userInfo')).nickname, // 默认值
    //recordDetailList: inspectionData.value.recordItemList
    recordDetailList: metricsItemTableData.value,
    startTime: startTime.value,
    endTime: endTime.value
  }

  console.log('提交检验结果:', { InspectionRecordVO: inspectionRecordVO })

  await InspectionRecordApi.createInspectionRecord(inspectionRecordVO)

  message.success('提交成功')
  // 提交后可以清空数据
  serial.value = ''
  handleSerialClear()
}

// 处理清空事件
const handleSerialClear = () => {
  // 清空产线和工序
  queryParams.lineId = ''
  queryParams.processCode = ''
  inspectionData.value = null
  metricsItemTableData.value = []
  //console.log('物料序列号已清空，同时清空了产线和工序')
}

// 监听窗口大小变化和组件挂载时计算角度
onMounted(() => {
  calculateDiagonalAngle()
  window.addEventListener('resize', calculateDiagonalAngle)
})
</script>
<style>
.serial-number {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-top: 50px; /* 调整上边距 */
  margin-bottom: 40px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.report-btn-container {
  text-align: center;
  margin-bottom: 30px; /* 增加底部间距 */
}

.report-btn {
  width: 220px;
  height: 160px;
  font-size: 48px;
}

.serial-input {
  width: 500px; /* 调整宽度 */
  /* height: 50px; 调整高度 */
  font-size: 18px; /* 增大字体 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.execute-type {
  width: 100px; /* 调整宽度 */
  /* height: 50px; */
  font-size: 18px; /* 增大字体 */ /* 调整高度 */
  border: 1px solid #ffffff;
  /* background: #0483e8; */
}

/* 新增样式 */
.inspection-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  align-items: center;
  color: #666;
}

.info-label {
  font-weight: bold;
  color: #666;
}

.info-value {
  margin-left: 5px;
  color: #666;
}

.inspection-items h3 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #666;
}

.action-buttons {
  text-align: center;
  float: right;
}

.action-buttons .el-button {
  margin: 0 10px;
  padding: 12px 25px;
  font-size: 16px;
}

:v-deep(.el-select) {
  height: 500px !important;
}

.ellipsis {
  display: inline-block;
  width: 200px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/*---------------*/

.inspection-table {
  width: 100%;
  margin-top: 10px;
}

/* ✅ 固定宽高的滚动容器 */
.table-scroll-wrapper {
  max-height: 600px; /* 你想固定的表格显示高度 */
  max-width: 100%; /* 或设置成 800px 等固定值 */
  overflow: auto; /* 水平 + 垂直都可以滚动 */
  border: 1px solid #ccc;
}

/* 表格本体 */
.custom-table {
  width: 100%;
  min-width: 600px; /* 保证有横向滚动空间 */
  border-collapse: collapse;
  table-layout: fixed;
  text-align: center;
}

/* 表头、单元格基本样式 */
.custom-table th {
  border: 1px solid #ccc;
  /* padding: 4px; */
  text-align: center;
  white-space: nowrap; /* 不换行，确保横向可滚 */
}

.custom-table {
  width: auto; /* 改为自动宽度 */
  min-width: 100%; /* 保证最小宽度填满容器 */
  table-layout: fixed; /* 保持固定布局 */
}

.sticky-header {
  min-width: 200px; /* 设置最小列宽 */
  position: sticky;
  z-index: 10;
  background: #f8f8f8;
}

.table-scroll-wrapper::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
.table-scroll-wrapper::-webkit-scrollbar-thumb {
  background-color: rgba(144,147,153,.3);
  border-radius: 8px;
}
.table-scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: rgba(144,147,153,.5);
}

.custom-table td {
  border: 1px solid #ccc;
  height: 60px;
  padding-left: 30px;
  padding-right: 30px;
  text-align: center;
  white-space: nowrap; /* 不换行，确保横向可滚 */

  .el-input__wrapper {
    border: 1px solid #070707;
  }
}

.custom-table td .el-input__inner {
  border-width: 2px;
  border-color: #409eff;
}

/* 确保下拉菜单显示在最上层 */
.el-select__popper {
  z-index: 100000 !important;
}

/* 斜线表头 */
.diagonal-header {
  width: 15%;
  position: sticky;
  height: 60px;
  background: #ddd;
  padding: 0;
  z-index: 99999;
  overflow: hidden;
}

/*diagonal-header {
  position: relative;
  top: 0;
  left: 0;
  z-index: 30; !* 比其他 th、td 更高，确保覆盖 *!
  width: 120px;
  height: 60px;
  background: #ddd;
  overflow: hidden;
  border: 1px solid #ccc;
}*/

/* .diagonal-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: var(--diagonal-width, 104%);
  height: 100%;
  border-top: 1px solid #606266;
  transform: rotate(var(--diagonal-angle, 13deg));
  transform-origin: top left;
  z-index: 1;
} */

/* 文本放角落 */
.top-text {
  position: absolute;
  top: 4px;
  right: 6px;
  font-size: 16px;
  z-index: 2;
  color: #606266;
}

.bottom-text {
  position: absolute;
  bottom: 4px;
  left: 6px;
  font-size: 16px;
  z-index: 2;
  color: #606266;
}

/* ✅ 表头固定（非左上） */
.sticky-header {
  position: sticky;
  top: 0;
  background: #f8f8f8;
  z-index: 10;
  color: #606266;
}

/* ✅ 左侧 label 固定列 */
.sticky-column {
  position: sticky;
  left: 0;
  background: #f9f9f9;
  z-index: 20;
}

/* 编辑图标 */
.label-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  font-weight: bold;
}

.edit-icon {
  cursor: pointer;
  font-size: 16px;
}

/* 边框高亮 */
.cell-red .el-input__wrapper {
  border: 1px solid #f56c6c !important;
  background-color: #fef0f0;
}

.cell-green .el-input__wrapper {
  border: 1px solid #67c23a !important;
  background-color: #f0f9eb;
}
</style>
